package com.sdy.hospitalguard.biz.utils;

import com.sdy.common.utils.OsPathUtil;
import org.apache.commons.httpclient.methods.GetMethod;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author fb
 * @since 2020/05/15
 */
public class PdfUtils {

    public static void saveBase64(String base64, String key, String path) {
        if (key != null) {
            // base64解密
            base64 = cbcDecrypt(base64, key);
        }

        byte[] bytes = Base64.decode(base64);
        FileOutputStream fos = null;
        FileChannel out = null;
        try {
/*           File file=new File(path);
            BufferedOutputStream bout=new BufferedOutputStream(new FileOutputStream(file + ".txt"));
            bout.write(base64.getBytes());
            bout.flush();
            bout.close();*/

            int index = path.replace("\\", "/").lastIndexOf("/");
            File outDir = new File(path.substring(0, index));
            outDir.mkdirs();

            fos = new FileOutputStream(path);
            out = fos.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

            out.write(byteBuffer);
            byteBuffer.clear();
            out.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public static void save(String str, String path) {

        try {
            File file = new File(path);
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
            bout.write(str.getBytes());
            bout.flush();
            bout.close();

            //System.out.println("保存到文件");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String readFileToBase64(String path) throws Exception {
        File file = new File(OsPathUtil.convertWithOs(path));
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encode(buffer);
    }


    public static String readFileToString(String filePath) {
        StringBuffer sb = new StringBuffer();
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");
            BufferedReader br = new BufferedReader(isr);

            String lineTxt = null;
            while ((lineTxt = br.readLine()) != null) {
                sb.append(lineTxt);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    // base64解密
    public static String cbcDecrypt(String data, String key) {
        try {
            // 偏移向量
            String iv = "0123456789abcdef";
            byte[] encrypted1 = Base64.decode(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

            // 恢复密钥
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString.trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param url  文件路径
     * @param path 保存到本地的文件路径
     * @return 是否保存成功
     */
    public static boolean saveFromUrl(String url, String path) {
        GetMethod get = new GetMethod(url);
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        FileOutputStream fos = null;
        try {
            client.executeMethod(get);
            fos = new FileOutputStream(path);
            fos.write(get.getResponseBody());
            fos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            get.releaseConnection();
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

